package com.superme.filemanager.utils;

import com.alibaba.fastjson2.JSON;
import com.superme.common.constant.Constants;
import com.superme.common.enums.ExceptionCodeEnum;
import com.superme.common.exceptions.BusinessException;
import com.superme.common.util.DateUtil;
import com.superme.filemanager.pojo.entity.DeleteFile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Component
@Slf4j
public class MqUtils {
    @Resource
    private RabbitTemplate rabbitTemplate;

    //发送普通消息
    public void sendMessage(String exchange, String routingKey, Object message) {
        String jsonString = JSON.toJSONString(message);
        rabbitTemplate.convertAndSend(exchange, routingKey, jsonString);
    }

    //发送延时消息
    public void sendDelayMessage(String exchange, String routingKey, Integer second, Object message) {
        if (second == null) {
            sendMessage(exchange, routingKey, message);
        } else {
            if (second <= 0) {
                throw new BusinessException(ExceptionCodeEnum.OUT_OF_MAX_TIME);
            }
            checkSecond(second);
            String jsonString = JSON.toJSONString(message);
            rabbitTemplate.convertAndSend(exchange, routingKey, jsonString, message1 -> {
                message1.getMessageProperties().setDelay(second * 1000);
                message1.getMessageProperties().setContentType("application/json");
                return message1;
            });
        }
    }

    private void checkSecond(Integer second) {
        if (second > Constants.DELAYED_QUEUE_MAX_TIME) {
            throw new BusinessException(ExceptionCodeEnum.OUT_OF_MAX_TIME.getCode(), ExceptionCodeEnum.OUT_OF_MAX_TIME.getMessage());
        }

    }

    /**
     * 删除文件封装
     *
     * @param deleteFile 删除文件实体信息
     */
    public void deleteFile(DeleteFile deleteFile) {
        sendDelayMessage(Constants.DELAY_EXCHANGE_NAME, Constants.DELAY_ROUTING_KEY, Constants.TIME_ONE_HALF_MONTH, deleteFile);
        log.info("发送消息到消息队列，time：{}，message：{}", DateUtil.parseDate(LocalDateTime.now()), deleteFile);
    }
}
